package com.lili.greedy;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: 李 力
 * @Date: 2024/8/6
 * @Description: 零钱兑换-最少的硬币个数
 * @version: 1.0
 */
public class Leetcode322 {

    //最少的硬币数:-1，无解
    private static int min = -1;

    /*
     * 方法一:暴力递归
     * 时间复杂度: O(coins.len^2)
     * 空间复杂度: O(1)
     * */
    public static int coinChange(int[] coins, int amount) {
        def(0, coins, amount, new AtomicInteger(-1));
        return min;
    }

    //count:代表某一种组合钱币的总数
    private static void def(int index, int[] coins, int less, AtomicInteger count) {
        count.incrementAndGet();
        if (less == 0) {
            if (min == -1) {
                min = count.get();
            } else {
                min = Math.min(min, count.get());
            }
        } else if (less > 0) {
            for (int i = index; i < coins.length; i++) {
                def(i, coins, less - coins[i], count);
            }
        }
        count.decrementAndGet();
    }

    /*
     * 方法二：贪心算法，前提是coins数组为降序则效率更高,但是贪心算法
     * 时间复杂度: O(coins.len)
     * 空间复杂度: O(1)
     * */
    public static int coinChange2(int[] coins, int amount) {
        //每次循环找到最优解:面值最大的硬币，它凑出来的硬币数最小
        int remainder = amount;
        int count = 0;
        for (int coin : coins) {
            while (remainder > coin) {
                remainder = remainder - coin;
                count++;
            }
            if (remainder == coin) {
                remainder = 0;
                count++;
                break;
            }
        }
        if (remainder > 0) {
            return -1;
        } else {
            return count;
        }
    }

    /*
     * 方法三:动态规划
     * 时间复杂度: O(coins.len^2)
     * 空间复杂度: O(1)
     * */
    public static int coinChange3(int[] coins, int amount) {
        int max = amount + 1;
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, max); //[1,3,5]  15
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.length; j++) {
                if (coins[j] <= i) {
                    dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }

}
